<?php
/**
 *
 *
 * @author Zeon <scplay@gmail.com>
 * @date 2019/5/29
 * @copyright PanxSoft Inc.
 */
namespace App\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;

/**
 * Class Language - 语言
 *
 * @property int $id - primary key
 * @property int $language_id
 * @property string $code
 *
 * @package App\Models
 * @mixin Builder
 */
class Language extends Model
{
    const STATUS_ENABLE = 1;
    const STATUS_DISABLE = 0;

    const LANGUAGE_ZH_CN_ID = 1;
    const LANGUAGE_EN_GB_ID = 3;

    /**
     * 常量名应与目录 resources\lang\{dir_name} 中的 dir_name 对应
     */
    const CODE_FALLBACK = "zh-cn";

    const IS_SHOW = 1; // 无法找到对应 CODE 时的默认语言

    protected static $unguarded = true;

    protected $table = 'languages';

    /**
     * @param string $code
     *
     * @return Language|null
     */
    public static function findByCode(string $code): ?self
    {
        return (new self)->where(compact('code'))->first();
    }

    /**
     * @param string $code
     *
     * @return Language|null
     */
    public static function memoFindByCode(string $code): ?self
    {
        static $code_lang_map = [
            // 'zh-cn' => LanguageModel
        ];

        if (key_exists($code, $code_lang_map)) {
            return $code_lang_map[$code];
        } else {
            return $code_lang_map[$code] = (new self)
                ->where('is_show', self::IS_SHOW)
                ->where(compact('code'))
                ->first();
        }
    }

    /**
     * @return Language
     */
    public static function default(): self
    {
        static $default = null;

        return $default ?: ($default = (new self)->oldest('sort_order')->first());
    }
}
